package com.jhgsys.internal.incentive.service.impl;

import com.jhgsys.internal.base.entity.BaseGoods;
import com.jhgsys.internal.base.service.IBaseGoodsService;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.incentive.dto.IncentiveQuotaApplyDto;
import com.jhgsys.internal.incentive.dto.IncentiveQuotaConfigDto;
import com.jhgsys.internal.incentive.entity.IncentiveQuotaConfig;
import com.jhgsys.internal.incentive.entity.IncentiveQuotaGoods;
import com.jhgsys.internal.incentive.entity.IncentiveRewardConfig;
import com.jhgsys.internal.incentive.entity.IncentiveRewarded;
import com.jhgsys.internal.incentive.mapper.IncentiveQuotaConfigMapper;
import com.jhgsys.internal.incentive.service.IIncentiveQuotaConfigService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.incentive.service.IIncentiveQuotaGoodsService;
import com.jhgsys.internal.incentive.service.IIncentiveRewardConfigService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 开单人额度设置 Service实现
 *
 * @author zhangwei
 * @date 2024-08-30 09:28:03
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class IncentiveQuotaConfigServiceImpl extends ServiceImpl<IncentiveQuotaConfigMapper, IncentiveQuotaConfig> implements IIncentiveQuotaConfigService {

    @Autowired
    private IIncentiveQuotaGoodsService incentiveQuotaGoodsService;

    @Autowired
    private IIncentiveRewardConfigService incentiveRewardConfigService;

    @Autowired
    private IBaseGoodsService baseGoodsService;

    /**
     * 查询（分页）
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     * @param request QueryRequest
     * @param incentiveQuotaConfig incentiveQuotaConfig
     * @return IPage<IncentiveQuotaConfig>
    */
    @Override
    public IPage<IncentiveQuotaConfig> findIncentiveQuotaConfigPage(QueryRequest request, IncentiveQuotaConfig incentiveQuotaConfig) {
        LambdaQueryWrapper<IncentiveQuotaConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IncentiveQuotaConfig::getDeletedFlg, 0);
        // TODO 设置查询条件
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getTenantId())){
            queryWrapper.eq(IncentiveQuotaConfig::getTenantId,incentiveQuotaConfig.getTenantId());
        }
        if(incentiveQuotaConfig.getYear()!=null){
            queryWrapper.eq(IncentiveQuotaConfig::getYear,incentiveQuotaConfig.getYear());
        }
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getRealName())){
            queryWrapper.like(IncentiveQuotaConfig::getRealName,incentiveQuotaConfig.getRealName());
        }
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getUserNo())){
            queryWrapper.like(IncentiveQuotaConfig::getUserNo,incentiveQuotaConfig.getUserNo());
        }
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getDeptName())){
            queryWrapper.like(IncentiveQuotaConfig::getDeptName,incentiveQuotaConfig.getDeptName());
        }

        Page<IncentiveQuotaConfig> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<IncentiveQuotaConfig> pages = this.page(page, queryWrapper);
        IPage<IncentiveQuotaConfig> result = new Page<>(request.getPageNum(), request.getPageSize());
        List<IncentiveQuotaConfig> list = pages.getRecords();
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(i->{
                i.setPenaltyBonusRatio(i.getPenaltyBonusRatio().multiply(BigDecimal.valueOf(100)));
            });
        }
        result.setRecords(list);
        result.setTotal(list.size());
        return result;
    }

    /**
     * 查询（所有）
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     * @param incentiveQuotaConfig incentiveQuotaConfig
     * @return List<IncentiveQuotaConfig>
     */
    @Override
    public List<IncentiveQuotaConfig> findIncentiveQuotaConfigList(IncentiveQuotaConfig incentiveQuotaConfig) {
	    LambdaQueryWrapper<IncentiveQuotaConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IncentiveQuotaConfig::getDeletedFlg, 0);
		// TODO 设置查询条件
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getTenantId())){
            queryWrapper.eq(IncentiveQuotaConfig::getTenantId,incentiveQuotaConfig.getTenantId());
        }
        if(null != incentiveQuotaConfig.getYear()){
            queryWrapper.eq(IncentiveQuotaConfig::getYear,incentiveQuotaConfig.getYear());
        }
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getUserId())){
            queryWrapper.eq(IncentiveQuotaConfig::getUserId,incentiveQuotaConfig.getUserId());
        }
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getStatus())){
            queryWrapper.eq(IncentiveQuotaConfig::getStatus,incentiveQuotaConfig.getStatus());
        }
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询（单条）
     *
     * @param incentiveQuotaConfig incentiveQuotaConfig
     * @return List<IncentiveQuotaConfig>
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     */
    @Override
    public IncentiveQuotaConfig findIncentiveQuotaConfig(IncentiveQuotaConfig incentiveQuotaConfig) {
        LambdaQueryWrapper<IncentiveQuotaConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IncentiveQuotaConfig::getDeletedFlg, 0);
        // TODO 设置查询条件
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getTenantId())){
            queryWrapper.eq(IncentiveQuotaConfig::getTenantId,incentiveQuotaConfig.getTenantId());
        }
        if(null != incentiveQuotaConfig.getYear()){
            queryWrapper.eq(IncentiveQuotaConfig::getYear,incentiveQuotaConfig.getYear());
        }
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getUserId())){
            queryWrapper.eq(IncentiveQuotaConfig::getUserId,incentiveQuotaConfig.getUserId());
        }
        if(StringUtils.isNotBlank(incentiveQuotaConfig.getStatus())){
            queryWrapper.eq(IncentiveQuotaConfig::getStatus,incentiveQuotaConfig.getStatus());
        }
        return this.baseMapper.selectOne(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author zhangwei
    * @date 2024-08-30 09:28:03
    * @param id
    * @return IncentiveQuotaConfig
    */
    @Override
    public IncentiveQuotaConfigDto findIncentiveQuotaConfigById(String id){
        IncentiveQuotaConfig incentiveQuotaConfig = this.baseMapper.selectById(id);
        if(incentiveQuotaConfig != null){
            IncentiveQuotaConfigDto incentiveQuotaConfigDto = BeanHelper.copyProperties(incentiveQuotaConfig,IncentiveQuotaConfigDto.class);
            incentiveQuotaConfigDto.setPenaltyBonusRatio(incentiveQuotaConfigDto.getPenaltyBonusRatio().multiply(BigDecimal.valueOf(100)));
            IncentiveQuotaGoods query = new IncentiveQuotaGoods();
            query.setQuotaConfigId(incentiveQuotaConfigDto.getQuotaConfigId());
            List<IncentiveQuotaGoods> goodsList = incentiveQuotaGoodsService.findIncentiveQuotaGoodsList(query);
            incentiveQuotaConfigDto.setGoodsList(goodsList);
            return incentiveQuotaConfigDto;
        }else{

            return new IncentiveQuotaConfigDto();
        }
    }

    /**
     * 根据userId查询
     *
     * @param userId
     * @return IncentiveQuotaConfig
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     */
    @Override
    public IncentiveQuotaConfigDto findIncentiveQuotaConfigByUserId(String userId) {
        IncentiveQuotaConfigDto dto = new IncentiveQuotaConfigDto();
        LambdaQueryWrapper<IncentiveQuotaConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IncentiveQuotaConfig::getDeletedFlg, 0);
        // TODO 设置查询条件
        queryWrapper.eq(IncentiveQuotaConfig::getYear, Calendar.getInstance().get(Calendar.YEAR));
        queryWrapper.eq(IncentiveQuotaConfig::getUserId,userId);
        queryWrapper.eq(IncentiveQuotaConfig::getStatus,"1");
        List<IncentiveQuotaConfig> configs = this.baseMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(configs)){
            dto = BeanHelper.copyProperties(configs.get(0),IncentiveQuotaConfigDto.class);
            dto.setPenaltyBonusRatio(dto.getPenaltyBonusRatio().multiply(BigDecimal.valueOf(100)));
            return dto;
        }else{
            return null;
        }
    }

    /**
     * 新增
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     * @param incentiveQuotaConfigDto incentiveQuotaConfigDto
     */
    @Override
    @Transactional
    public void createIncentiveQuotaConfig(IncentiveQuotaConfigDto incentiveQuotaConfigDto) {
        IncentiveQuotaConfig incentiveQuotaConfig = BeanHelper.copyProperties(incentiveQuotaConfigDto,IncentiveQuotaConfig.class);
        incentiveQuotaConfig.setCreatedTime(new Date());
        incentiveQuotaConfig.setRewardedQuota(BigDecimal.valueOf(0));
        incentiveQuotaConfig.setPenaltyBonusRatio(incentiveQuotaConfigDto.getPenaltyBonusRatio().divide(BigDecimal.valueOf(100)));
        this.save(incentiveQuotaConfig);
        if(!CollectionUtils.isEmpty(incentiveQuotaConfigDto.getGoodsList())){
            List<IncentiveQuotaGoods> goodsList = incentiveQuotaConfigDto.getGoodsList();
            goodsList.forEach(i->{
                i.setTenantId(incentiveQuotaConfigDto.getTenantId());
                i.setQuotaConfigId(incentiveQuotaConfig.getQuotaConfigId());
                i.setFileName(i.getGoodsName());
                i.setCreatedBy(incentiveQuotaConfigDto.getCreatedBy());
                i.setCreatedTime(new Date());
            });
            incentiveQuotaGoodsService.saveBatch(goodsList);
        }
    }

    /**
     * 修改
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     * @param incentiveQuotaConfigDto incentiveQuotaConfigDto
     */
    @Override
    @Transactional
    public void updateIncentiveQuotaConfig(IncentiveQuotaConfigDto incentiveQuotaConfigDto) {
        IncentiveQuotaConfig incentiveQuotaConfig = BeanHelper.copyProperties(incentiveQuotaConfigDto,IncentiveQuotaConfig.class);
        incentiveQuotaConfig.setUpdatedTime(new Date());
        incentiveQuotaConfig.setPenaltyBonusRatio(incentiveQuotaConfigDto.getPenaltyBonusRatio().divide(BigDecimal.valueOf(100)));
        this.saveOrUpdate(incentiveQuotaConfig);
        if(!CollectionUtils.isEmpty(incentiveQuotaConfigDto.getGoodsList())){
            incentiveQuotaGoodsService.deleteInceniveQUatGoodsById(incentiveQuotaConfig.getQuotaConfigId(),incentiveQuotaConfigDto.getCreatedBy());
            List<IncentiveQuotaGoods> goodsList = incentiveQuotaConfigDto.getGoodsList();
            goodsList.forEach(i->{
                i.setTenantId(incentiveQuotaConfigDto.getTenantId());
                i.setQuotaConfigId(incentiveQuotaConfig.getQuotaConfigId());
                i.setFileName(i.getGoodsName());
                i.setCreatedBy(incentiveQuotaConfigDto.getCreatedBy());
                i.setCreatedTime(new Date());
            });
            incentiveQuotaGoodsService.saveBatch(goodsList);
        }else{
            incentiveQuotaGoodsService.deleteInceniveQUatGoodsById(incentiveQuotaConfig.getQuotaConfigId(),incentiveQuotaConfigDto.getCreatedBy());
        }
    }

    /**
     * 逻辑删除
     * @author zhangwei
     * @date 2024-08-30 09:28:03
     * @param incentiveQuotaConfig incentiveQuotaConfig
     * @param incentiveQuotaConfigIds incentiveQuotaConfigIds
     */
    @Override
    @Transactional
    public void deleteIncentiveQuotaConfig(IncentiveQuotaConfig incentiveQuotaConfig,String incentiveQuotaConfigIds) {
        List<String> list = Arrays.asList(incentiveQuotaConfigIds.split(StringPool.COMMA));
        this.baseMapper.update(incentiveQuotaConfig,new LambdaQueryWrapper<IncentiveQuotaConfig>().in(IncentiveQuotaConfig::getQuotaConfigId,list));
	}

    /**
    * 物理删除
    * @author zhangwei
    * @date 2024-08-30 09:28:03
    * @param incentiveQuotaConfigIds incentiveQuotaConfigIds
    */
    @Override
    @Transactional
    public void physicallyDeleteIncentiveQuotaConfig(String incentiveQuotaConfigIds) {
        List<String> list = Arrays.asList(incentiveQuotaConfigIds.split(StringPool.COMMA));
        LambdaQueryWrapper<IncentiveQuotaConfig> wapper = new LambdaQueryWrapper<>();
        wapper.in(IncentiveQuotaConfig::getQuotaConfigId,list);
        this.remove(wapper);
    }

    /**
     * 更新已奖励额度
     *
     * @param rewardedList
     * @author zhangwei
     * @date 2024-09-03 11:13:45
     */
    @Override
    public void updateIncentiveRewardedQuota(List<IncentiveRewarded> rewardedList) throws FebsException {
        if(!CollectionUtils.isEmpty(rewardedList)){
            rewardedList.forEach(rewarded -> {
                IncentiveQuotaConfig query = new IncentiveQuotaConfig();
                query.setYear(Calendar.getInstance().get(Calendar.YEAR));
                query.setUserId(rewarded.getUserId());
                query.setStatus("1");
                IncentiveQuotaConfig incentiveQuotaConfig = this.findIncentiveQuotaConfig(query);
                if(null != incentiveQuotaConfig){
                    BigDecimal rewardedQuota = incentiveQuotaConfig.getRewardedQuota() == null? BigDecimal.valueOf(0):incentiveQuotaConfig.getRewardedQuota();
                    BigDecimal quantity = rewarded.getRewardQuantity();
                    switch (rewarded.getRewardType()){
                        //奖金
                        case "0":
                            incentiveQuotaConfig.setRewardedQuota(rewardedQuota.add(quantity));
                            break;
                        //奖品
                        case "1":
                            String goodsId = rewarded.getRewardKey();
                            BaseGoods goods = baseGoodsService.findBaseGoodsById(goodsId);
                            if(goods != null){
                                incentiveQuotaConfig.setRewardedQuota(rewardedQuota.add(quantity.multiply(goods.getGoodsPrice())));
                            }
                            break;
                        //积分
                        case "2":
                            IncentiveRewardConfig incentiveRewardConfig = incentiveRewardConfigService.findIncentiveRewardConfigByTenantId(rewarded.getTenantId());
                            if(!ObjectUtils.isEmpty(incentiveRewardConfig)){
                                if(!ObjectUtils.isEmpty(incentiveRewardConfig.getScoreAmountRatio())){
                                    incentiveQuotaConfig.setRewardedQuota(rewardedQuota.add(quantity.multiply(incentiveRewardConfig.getScoreAmountRatio())));
                                }else{
                                    incentiveQuotaConfig.setRewardedQuota(rewardedQuota.add(quantity));
                                }
                            }else{
                                incentiveQuotaConfig.setRewardedQuota(rewardedQuota.add(quantity));
                            }
                            break;
                    }
                    this.saveOrUpdate(incentiveQuotaConfig);
                }
            });
        }else{
            throw new FebsException("请传入有效的奖品数据");
        }

    }
}
